<?php

/**
* AdminRemoveGuideFormModule.class.php
*
* Concrete page module responsable for creating guide remove page
*
* @author     Blazej Zieba <b@zieba.info>
* @copyright  2007 konekto.com
* @version    CVS: $Id:$
*/

require_once("framework/PageModule.class.php");
require_once("MDB2.php");
require_once("HTML/QuickForm.php");
require_once("HTML/QuickForm/Renderer/Default.php");
require_once("framework/Yt.class.php");



HTML_QuickForm::registerRule('NumericOrNull','callback','numericOrNull');

// {{{ SlideShowListModule

class AdminRemoveGuideFormModule extends PageModule 
{
    
    private $dbh;
    // {{{ Class operations 

    // {{{ SlideShowListModule
    /**
    * C'tor
    */
    
    function AdminRemoveGuideFormModule()
    {
        trigger_error("ENTER AdminRemoveGuideFormModule::AdminRemoveGuideFormModule()", E_USER_NOTICE);
        $options = &PEAR::getStaticProperty('CONFIG_INI','DSN');    
        $this->dbh = new PDO($options['dsn_string']);
        $this->dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    // }}}
    // {{{ getContent

    /**
    * Function returns page content
    *
    */

    function getContent()
    {
        
        trigger_error("ENTER AdminRemoveGuideFormModule::getContent()", E_USER_NOTICE);
        $form = new HTML_QuickForm("RemoveGuideForm", 'post', 'index.php?cmd=AdminRemoveGuide');
        $options = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

        $form->addElement('hidden','id', isset($_GET['id']) ? $_GET['id'] : null);

        $group[] =& HTML_QuickForm::createElement('submit','Submit', _('Tak'));
        $group[] =& HTML_QuickForm::createElement('submit','cancel', _('Nie'));
        $form->addGroup($group, null, null, '&nbsp;');

        $form->addRule('id', '', null,'required');

        $options = &PEAR::getStaticProperty('CONFIG_INI','TEMPLATES');     
        $statusTpl = new HTML_Template_IT($options["templates_dir"]);
        $statusTpl->loadTemplatefile("status.tpl.xhtml",FALSE,FALSE);

        if ($form->validate()) 
        {
            $data =  $form->getSubmitValues(true);
            if( isset($data['cancel']) )
            {
                $global = &PEAR::getStaticProperty('CONFIG_INI','GLOBAL');

                header("Location: ".$global['service_url']."?cmd=AdminGuideList");
            }
            elseif ( $form->getSubmitValue( 'id' ) )
            {
                $this->removeGuide( $data );
                $statusTpl->setVariable("STATUS",_("Trasa usunięta."));
            }
            return $statusTpl->get();

        }
        else
        {
 
            $renderer =& new HTML_QuickForm_Renderer_Default($options);
            $renderer -> setFormTemplate(file_get_contents($options["templates_dir"]."form.tpl.xhtml"));
            $renderer -> setElementTemplate(file_get_contents($options["templates_dir"]."formElement.tpl.xhtml"));
            $renderer -> setRequiredNoteTemplate(file_get_contents($options["templates_dir"]."formRequiredNote.tpl.xhtml"));
            $form -> setRequiredNote(null); 
            $form->accept($renderer);

            $sth = $this->dbh->prepare("SELECT name FROM  guide WHERE rowid = :id AND owner = :owner");
            $sth -> bindParam(':id',  $_GET['id'] ,PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);    
            $sth->execute();
            $resultName = $sth->fetchColumn();

            $sth = $this->dbh->prepare("SELECT COUNT(name) FROM slide WHERE guide_id = :id AND owner = :owner");
            $sth->bindParam(':id',  $_GET['id'] ,PDO::PARAM_INT);
            $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);    
            $sth->execute();
            $resultCount = $sth->fetchColumn();

            $statusTpl->setVariable("STATUS",sprintf(_("Usunąć trasę %s razem z %s slajdami ?"), $resultName, $resultCount));

	        return $statusTpl->get().$renderer->toHtml().$statusTpl->get();
        }

    }
    
    // }}}

    // {{{ removeGuide

    /**
    * Function to remove guide data 
    *
    */
    private function removeGuide($data)
    {
        
        trigger_error("ENTER AdminRemoveGuideFormModule::addSlide()", E_USER_NOTICE); 

        if ( ! $this->dbh->beginTransaction() )
        {
            trigger_error("AdminRemoveGuideFormModule::removeGuide()  Nie można rozpocząć tranzakcji !", E_USER_ERROR);
        }

        //Clean up data from slides 
        $sth = $this->dbh->prepare("SELECT video_file FROM slide WHERE guide_id = :id AND owner = :owner") ;
        $sth -> bindParam(':id',$data['id'],PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);    
        $sth->execute();

        while ( $row = $sth->fetch(PDO::FETCH_ASSOC) )
        {
            
            //Remove video from YouTube
            if ( $row['video_file'] != '')
            {
                $yt = Yt::getClient();
        
                try
                {
                    $videoEntry = $yt->getVideoEntry($row['video_file'],null,true);
                    $yt->delete($videoEntry);
                }
                catch(Zend_Gdata_App_HttpException $e)
                {
                   trigger_error("AdminRemoveSlideFormModule:: deleteVideoFromYt() Could not remove video id =  ".$row['video_file'], E_USER_WARNING );
                }

            }

        }
        
        //Remove slide
        $sth = $this->dbh->prepare("DELETE FROM slide WHERE guide_id = :id AND owner = :owner") ;
        $sth -> bindParam(':id',$data['id'],PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);    
        $sth->execute();

        $sth = $this->dbh->prepare("DELETE FROM guide WHERE rowid = :id AND owner = :owner") ;
        $sth -> bindParam(':id',$data['id'],PDO::PARAM_INT);
        $sth -> bindParam(':owner',  AuthSingleton::instance()->getUsername() ,PDO::PARAM_STR);    
        $sth->execute();

        if ( ! $this->dbh->commit() )
        {
            trigger_error("AdminRemoveGuideFormModule::removeGuide()  Nie można zakończyć tranzakcji !", E_USER_ERROR);
        }
    }

    // }}}

}

// }}} 

?>
